python count files fast

32

import os
dir_path='C:/route/to/dir'
# Example 1: Non-recursive
tree=os.walk(dir_path, topdown=True)
top_branch=next(tree)
print(len(top_branch[2]))   
# The result is 3
# Example 2: Non-recursive (a more compact form)
tree=os.walk(dir_path, topdown=True)
print(len(next(tree)[2]))   
# The result is 3  
# Example 4: Recursive
num=0
for i in os.walk(dir_path, topdown=True):
    num += len(i[2]) 
print(num)   
# The result is 4

# any of these is equaly fast

Comments

Submit
0 Comments